.net 6 mvc with react ERR_CONNECTION_REFUSED - reactjs

console error is
ERR_CONNECTION_REFUSED and Uncaught (in promise) AxiosError {message: 'Network Error', name: 'AxiosError', code: 'ERR_NETWORK' ~
like this:
controller
[ApiController]
[Route("api/[controller]")]
public class AccountController : ControllerBase
{
private readonly IHaruUserRepository _repository;
private readonly ILogger _logger;
public AccountController(IHaruUserRepository repository, ILoggerFactory loggerFactory)
{
this._repository = repository ?? throw new ArgumentNullException(nameof(AccountController));
this._logger = loggerFactory.CreateLogger(nameof(AccountController));
}
[HttpGet] // [HttpGet("[action]")]
public async Task<IActionResult> GetAll()
{
try
{
var models = await _repository.GetAllAsync();
if (!models.Any())
{
return new NoContentResult();
}
return Ok(models);
}
catch (Exception e)
{
_logger.LogError(e.Message);
return BadRequest();
}
}
function
async handleSubmit(e) {
e.preventDefault();
await axios.get("/api/account").then(result => {
});
}

I added 'services.AddTransient<'interface name of repository', 'repository name'>();' in DI Container.

Related

How post data in ASP.NET Core (frontend to backend (React))

It is my react code to hit the API on submit button
I update the question and add a new class httpresponemessage post
const handleOnPreview = (e) => {
e.preventDefault();
setsubmittext(text);
const ROOT_URL='https://localhost:7113/';
axios.post(`${ROOT_URL}/api/demo-text`, text, {
headers: { 'Content-type':'application/json'}
})
}
This is my controller in ASP.NET Core MVC:
public class HomeController: Controller
{
private readonly ILogger<HomeController> _logger;
public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
}
public IActionResult Index()
{
return View();
}
[HttpPost]
[Route("/api/demo-text")]
[EnableCors("AllowOrigin")]
public HttpResponseMessage Post([FromForm] text text)
{
return new HttpResponseMessage()
{
Content = new StringContent("POST: Test message")
};
}
public IActionResult Privacy()
{
return View();
}
}
Startup.cs
this is the middleware file of my project
MiddleWare
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCors();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
last error I get
I want the HTTP post method to post the data.
If you have not yet, you need to define the cors policy in your asp.net core.
In Startup class:
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy(options.DefaultPolicyName,
policy => policy.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod());
});
}
and in your configuration of the HTTP request pipeline method
public async void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
// ... other middlewares
app.UseCors();
// ... other middlewares
}
Attention: this allows for any origin and may cause security problems. Just do that for checking and testing. Not suggested in production.

Can you redirect exception handling to URLs in ASP.NET?

I'm working on a ASP.NET Core application with ReactJS and I'd like unhandled exceptions to have their data redirected to a particular route (URL to a React Component). For instance, suppose I have a controller as follows:
public class StartProblemsController : ControllerBase
{
[HttpGet]
public ActionResult Get()
{
int a = 1;
int b = 0;
int err = a / b;
return Ok();
}
}
This clearly throws an DivideByZero exception at runtime when routed to. However, the exception is only displayed in the console and the front-end silently fails by displaying me a blank web page. I've got the following middleware:
app.UseExceptionHandler("/error");
app.UseHsts();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseSpaStaticFiles();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller}/{action=Index}/{id?}");
});
app.UseSpa(spa =>
{
spa.Options.SourcePath = "ClientApp";
if (env.IsDevelopment())
{
spa.UseReactDevelopmentServer(npmScript: "start");
}
});
I would think that app.UseExceptionHandler("/error") would do the trick and would redirect the browser to https://.../error but it doesn't. It remains at https://.../startproblems. Any suggestions? Thanks in advance.
React runs through npm, server routing will be overwritten by react, and react requests data through ajax, so it will not be redirected to server. A better method is to write the error to the page directly.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseExceptionHandler(builder =>
{
builder.Run(async context =>
{
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
context.Response.ContentType = "application/json";
var exception = context.Features.Get<IExceptionHandlerFeature>();
if (exception != null)
{
var error = new ErrorMessage()
{
Stacktrace = exception.Error.StackTrace,
Message = exception.Error.Message
};
var errObj = JsonConvert.SerializeObject(error);
await context.Response.WriteAsync(errObj).ConfigureAwait(false);
}
});
});
//...
}
Class
public class ErrorMessage
{
public string Stacktrace { get; set; }
public string Message { get; set; }
}
If you can not view the error message, open the browser's console, click the server error.
Then, it will navigate to the error code.

Why API method never fired?

I have this API methods:
namespace Playground.Web.Controllers.API
{
public class FilterConfigurationsController : ApiController
{
private readonly PlaygroundContext _context;
public FilterConfigurationsController()
{
_context = new PlaygroundContext();
}
[HttpPost]
public async Task<IHttpActionResult> Post(Filter data)
{
try
{
var ere = FilterViewModel.GenerateDataForFilters(data, _context);
return Ok(data);
}
catch (Exception ex)
{
throw;
}
}
[HttpPost]
public async Task<IHttpActionResult> Post(IEnumarable<Filter> filterDescriptionList)
{
try
{
var data = FilterViewModel.GenerateDataForFilters(filterDescriptionList, _context);
return Ok();
}
catch (Exception ex)
{
throw;
}
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
_context.Dispose();
}
base.Dispose(disposing);
}
}
}
To call this methods I use this HTTP post calls:
$http.post(config.baseUrl + "api/FilterConfigurations/", scope.filterParams).then(function (result) {});
I am working on web API project and using AngularJS in my project.
This HTTP post call:
$http.get(config.baseUrl + "api/FilterConfigurations/,{data= scope.filterParams[0]}).then(function (result) {});
have to call this method API:
public async Task Post(Filter data)en(function (result) {});
But the method API above never fired.
Instead this method alwaes fired:
public async Task<IHttpActionResult> Post(Filter filterDescriptionList)
Any idea why the API method never fired?
What I am doing wrong?

angular + ngStomp + spring websocket controller not executed

I have searched through all the tutorials and did exactly as explained there, but I can't reach my controller.
Here is my websocket xml config:
<websocket:handlers>
<websocket:mapping path="/updateHandler" handler="updateHandler"/>
<websocket:sockjs/>
</websocket:handlers>
<websocket:message-broker application-destination-prefix="/app">
<websocket:stomp-endpoint path="/update">
<websocket:sockjs/>
</websocket:stomp-endpoint>
<websocket:simple-broker prefix="/topic"/>
</websocket:message-broker>
I don't actually know do I need the handler, but without it stomp connection fails with "whoops! Lost connection to undefined".
Any suggestion in this direction is also welcome.
Here is my empty handler:
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
public class UpdateHandler extends TextWebSocketHandler {
#Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
}
}
And my controller
#RestController
public class WebSocketController {
#MessageMapping("/update")
#SendTo("/topic/messages")
public OutputMessage sendmMessage(Message message) {
return new OutputMessage(message, new Date());
}
}
I am using ngStomp from angular as suggested:
var message = {message: 'message body', id: 1};
$scope.testWebSocket = function () {
$stomp.setDebug(function (args) {
console.log(args + '\n');
});
$stomp.connect('/myAppContext/update', {})
.then(function (frame) {
var connected = true;
var subscription = $stomp.subscribe('/topic/messages', function (payload, headers, res) {
$scope.payload = payload;
}, {});
$stomp.send('/myAppContext/app/update', message);
subscription.unsubscribe();
$stomp.disconnect(function () {
console.error('disconnected');
});
}, function(error){
console.error(error);
});
};
My Message Class:
public class Message {
private String message;
private int id;
public Message() {
}
public Message(int id, String text) {
this.id = id;
this.message = text;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
My OutputMessage class:
public class OutputMessage extends Message {
private Date time;
public OutputMessage(Message original, Date time) {
super(original.getId(), original.getMessage());
}
public Date getTime() {
return time;
}
public void setTime(Date time) {
this.time = time;
}
when I execute the testWebSocket() I get following output:
Opening Web Socket...
Web Socket Opened...
>>> CONNECT
accept-version:1.1,1.0
heart-beat:10000,10000
<<< CONNECTED
version:1.1
heart-beat:0,0
user-name:user#domain.com
connected to server undefined
>>> SUBSCRIBE
id:sub-0
destination:/topic/messages
>>> SEND
destination:/myAppContext/app/update
content-length:33
{"message":"message body","id":1}
Why connected to server undefined?
And why my controller never gets executed after sending a message?
I am using spring-4.1.4 with security-core-3.2.5 and Tomcat server 8.0.18
As a non-pretty workaround, I moved websocket configuration to the Java config and it works.
Config below:
#Configuration
#EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
#Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic");
config.setApplicationDestinationPrefixes("/app");
}
#Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/update")
.withSockJS();
}
I actually don't know why.

Handling failed claim in Nancy

I am using the RequiresClaims mechanism in Nancy like this:
public class HomeModule : NancyModule
{
public HomeModule()
{
Get["/"] = ctx => "Go here";
Get["/admin"] = ctx =>
{
this.RequiresClaims(new[] { "boss" }); // this
return "Hello!";
};
Get["/login"] = ctx => "<form action=\"/login\" method=\"post\">" +
"<button type=\"submit\">login</button>" +
"</form>";
Post["/login"] = ctx =>
{
return this.Login(Guid.Parse("332651DD-A046-4489-B31F-B6FA1FB290F0"));
};
}
}
The problem is if the user is not allowed to enter /admin because the user doesn't have claim boss, Nancy just responds with http status 403 and blank body.
This is exactly what I need for the web service part of my application, but there are also parts of my application where nancy should construct page for user. How can I show something more informative to the user?
This is the user mapper that I use:
public class MyUserMapper : IUserMapper
{
public class MyUserIdentity : Nancy.Security.IUserIdentity
{
public IEnumerable<string> Claims { get; set; }
public string UserName { get; set; }
}
public Nancy.Security.IUserIdentity GetUserFromIdentifier(Guid identifier, Nancy.NancyContext context)
{
return new MyUserIdentity { UserName = "joe", Claims = new[] { "peon" } };
}
}
And this is the bootstrapper that I use:
public class MyNancyBootstrapper : DefaultNancyBootstrapper
{
protected override void RequestStartup(
Nancy.TinyIoc.TinyIoCContainer container, Nancy.Bootstrapper.IPipelines pipelines, NancyContext context)
{
base.RequestStartup(container, pipelines, context);
var formAuthConfig = new Nancy.Authentication.Forms.FormsAuthenticationConfiguration
{
RedirectUrl = "~/login",
UserMapper = container.Resolve<Nancy.Authentication.Forms.IUserMapper>()
};
Nancy.Authentication.Forms.FormsAuthentication.Enable(pipelines, formAuthConfig);
}
}
You need to handle the 403 status code as part of the pipeline and then return an html response to the user. Take a look at http://paulstovell.com/blog/consistent-error-handling-with-nancy

Resources