Deploy ASP.net core 2.1 WEB API to IIS using Visual Studio Code - asp.net-web-api

Working on an ASP.net core 2.1 web API project. I need to enable the API so that it can be accesed by client applications that we also have under developement.
So far, the only way I've found to publish to IIS is by doing a manual process:
Run dotnet publish -c Release
Copy the files in bin\Release\netcoreapp2.1\publish\ to my IIS Web App folder
I wonder if there is a more straight forward way of doing this.
Also It takes quite sometime to build this release, so for a development environment it's quite a slow process. The problem is that we cannot allow external access to the WEB api when running with F5 on the Integrated test server. How can we enable an more agile testing environment?
Another issue is that when calling for example fetch('MyAPIServer/api/MyItems') from a javascript application, I get a CORS error:
Failed to load http://localhost:86/api/shit: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8082' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled
Is enabling CORS absolutely necesary when developing this type of apps?
If I fetch like this:
fetch(
`http://localhost:86/api/shit`,{mode: 'no-cors'}
)
I get:
Uncaught (in promise) SyntaxError: Unexpected end of input
at eval (Pos.vue?7f37:68)

As far as the CORs issue goes you can add the following to your startup:
public void ConfigureServices(IServiceCollection services)
{
// Rest of config stuff ...
services.AddCors();
}
Then in you will also need to add the following.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseCors(builder =>
{
builder.WithOrigins("http://localhost:8080",
"http://localhost:8081",
"http://localhost:8082")
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials();
});
app.UseMvc();
}

Related

ASP.NET Core Web API - Exception is not showing immediately in Visual Studio

I have an exception thrown in my ASP.NET Core Web API project.
And I do get the exception name and stacktrace and everything, but the problem is that I get that as a response to the API request, but I want Visual Studio to take me immediately to the exception where and when it was thrown, like I have placed a breakpoint to it.
This is something that used to work in regular ASP.NET Core MVC projects, but for some reason it doesn't work in Web API.
Also, to clarify - I don't have any global exception handling filter or middleware, I just call app.UseDeveloperExceptionPage(); to get the detailed exception in development, this is from my HTTP request pipeline:
if (app.Environment.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI();
}
else
{
app.UseCustomExceptionHandler();
}
// Other irrelevant middlewares...
you need to set the Visual Studio like this:
link.
Based on #XinranShen answer I also needed to update the debug settings.
I checked the setting marked below:

Blazor app not running server code when on hosted server

I have a blazor web assembly app and I have 3 projects that were created. The client, server and shared. I assume all of these are deployed as standard when using the webdeploy?
The site works in that it displays the pages etc. However when I go to a page that contacts the server project via the Http.PostAsJsonAsync() method, I get the blazor error page (which I setup to say "oops").
Obviously I get no details as to what is going wrong. So I have no idea what is happening. Is the server app compiled into the Web assembly app? If so why would it not be running the server code? Plus I suppose the other question is how do I get it to report the error so that I can get an idea as to what is going wrong?
It works absolutely fine when running it through Visual Studio.
This is the first time I have deployed to a hosted server so there is a very high chance I have done something wrong...
The method I am calling literally does nothing other than returning a 200 message. So I assume the issue is with calling the server method itself.
Firstly, use Logging:
https://learn.microsoft.com/en-us/aspnet/core/blazor/fundamentals/logging?view=aspnetcore-5.0&pivots=server
#inject ILogger<MyComponent> Logger
Then wrap your Http.PostAsJsonAsync() call in a Try Catch block.
Log the error in the Catch block:
try
{
await Http.PostAsJsonAsync()
}
catch (Exception e)
{
Logger.LogError(e);
}
After deployment, edit your web.config file:
<aspNetCore processPath="dotnet"
arguments=".\Hospitillity.App.Server.dll"
stdoutLogEnabled="true" // <<< MAKE THIS true
stdoutLogFile=".\logs\stdout"
hostingModel="inprocess">
Note, the setting stdoutLogEnabled="true". This will cause your hosting provider to generate log files.
Then recycle your app pool on your hosting provider.
Connect to your website again, and after the error you should have some more details about error logged in
\logs\stdout_nnnnnnnnnnnnnn_nnnnnn.log
on the hosting server.
Take it from there ...

Web API works locally but doesn’t work on azure

I have created a web API connected to azure sql server in .net core using visual studio for Mac đź’». Then I created a web app in azure and then published by project directly in visual studio for Mac to azure.
After I published I try to access the api using postman and chrome (URL/api/menu) but I got 500 server error which is generic and doesn’t tell me anything.
In visual studio for Mac I got the green light it said published and directly took me to the new url.
So, what do you guys thing is the problem.
This is my first time using azure so I didn’t change any setting or anything
Since many different problems can cause this error page, I can strongly recommend the following in order to determine the root cause quickly and easily, without struggling with Azure (or any server/platform for that matter) to get logs.
You can enable extremely helpful error messages at startup by setting the .UseSetting("detailedErrors", "true") and .CaptureStartupErrors(true) actions in your Program.cs file.
For ASP.NET CORE 2.1
public class Program
{
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.CaptureStartupErrors(true)
.UseSetting("detailedErrors", "true")
.UseStartup<Startup>()
.Build();
}
Add these commands in your startup.cs class:
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
app.UseBrowserLink();
also enable stdoutLog in your web.config file
stdoutLogEnabled="true" stdoutLogFile=".\logs\stdout"
Error code 500 in web api,usually, means problems with a configuration in Startup.cs - the most common problems include an issue with DB itself, an issue with migrations (if you are using Code First approach), problems with appsettings.js.
Please refer to the log file in .\logs\stdout.
Hope it helps.

Swagger does not show real error message

We are on .NET WebAPI framework and we are using swagger on top of web api for annotations and out of the box UI experience. So far, it just has been working great. However, when I return an error from WebAPI(Http 400) as following code:
return BadRequest("Some error");
However, when I do that, it seems like Swagger is not able to parse the error properly. It basically, show response 0. Which is wrong for sure because when I go to Chrome DevTools, I see that my request had a response of HTTP 400 as I expected.
How can I configure Swagger so that it is able to show the errors correctly? Or should I be throwing my errors a little bit differently to be able to see it in swagger?
You can annotate your actions like this
[ProducesResponseType(typeof(ResponseObjectTypeHere), 200)]
[ProducesResponseType(typeof(ErrorResponseObjectTypeHere), 400)]
You can also add something like this in the xml documentation if you enable swagger to read and use xml documentation
/// <response code="200">Description</response>
/// <response code="400">Description of error</response>
I used those in the .net core web api project with swagger, should be the same for regular .net web api project as well.
You can simply send the exception details to the client by enabling one of ABP's configurations (SendAllExceptionsToClients) in ***.Web.Core Module, like this:
public override void PreInitialize()
{
if (_env.EnvironmentName.ToLower() == "development")
Configuration.Modules.AbpWebCommon().SendAllExceptionsToClients = true;
}
Then you get the exception details on the client. Recommended only during development.

How to create a custom Maintenance page returning 503 for Azure?

I'm trying to set up a custom Maintenance page on MVC 3 but specifically on Azure. Basically to keep it SEO friendly i need to return a 503 (Service Unavailable). All my other custom error pages work in Azure (eg 404) following the usual
<customErrors mode="On">
<error statusCode="404" redirect="404.htm"/>
<error statusCode="503" redirect="503.htm"/>
</customErrors>
The 404 page works but the 503 is not followed and i simply get an ugly service unavailable page. I have the 500 error working fine through error.cshtml and the standard HandleErrorAttribute.
I even try returning my own ActionResult from an ActionFilter by using the following
public class SiteDownForTestingResult : ActionResult
{
public SiteDownForTestingResult() : base()
{
}
public override void ExecuteResult(ControllerContext context)
{
var path = System.Web.Hosting.HostingEnvironment.MapPath("~/app_testing.htm");
var response = context.HttpContext.Response;
response.Clear();
response.StatusCode = (int)HttpStatusCode.ServiceUnavailable;
response.StatusDescription = "Service Unavailable.";
response.WriteFile(path);
response.End();
}
}
were app_testing is my custom page, and then setting the filterContext.Result = new SiteDownForTestingResult(); from OnActionExecuting of an ActionFilter and still i'm greeted by the plain 503 'service unavailable' page
Is this something to do with application.config on Azure locking something or other i don't know about. This works fine on IIS7 and my local box, but the Emulator and Cloud both give no joy.
Any help would be appreciated.
Based on my understanding custom 503 error is generated directly from https.sys mostly when app pool is not available. And now when there is no app pool none of your setting is going to work at your custom error settings will be specific to app pool. Also most of the search engine depend on 503 error code in return so display search result properly and that's why customization of this error is not typically done at application level.
As you referenced Windows Azure Emulator, I believe you are using Windows Azure Web Role. With Windows Azure Web Role you can customize IIS with AppCmd.exe in a StartUp task, which is your maximum level of customization. You can not reach HTTP.sys level of customization in Windows Azure so customization 503 error may not work on Windows Azure.

Resources