Angular2+ and ASP.NET WebAPI on IIS

6AM
Уже с Приветом
Posts: 602
Joined: 13 Mar 2019 14:57

Re: Angular2+ and ASP.NET WebAPI on IIS

Post by 6AM »

Вообще-то не так сложно это сделать - вот например :

IIS server folder structure:
C:\inetpub\web.site.com - IIS website folder
C:\inetpub\web.site.com\OData - folder for rest api project (.NET 4.6.x EF ASP.NET OData)
C:\inetpub\web.site.com\web.config

Build your Angular project using ex "ng build --prod --aot" and copy \dist content to the C:\inetpub\web.site.com\

Important: \dist\assets (if you have one) should be copied to C:\inetpub\web.site.com\assets

Example of C:\inetpub\web.site.com\web.config below:

Нужно будет установить https://www.iis.net/downloads/microsoft/url-rewrite

--- Azure instance --- IIS 10.x --- web.config ---
<configuration>
<system.webServer>

<rewrite>
<rules>
<rule name="OData" stopProcessing="true">
<match url="OData" />
<conditions logicalGrouping="MatchAll" trackAllCaptures="false" />
<action type="None" />
</rule>
<rule name="Angular Routes" stopProcessing="true">
<match url=".*" />
<conditions logicalGrouping="MatchAll">
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
<add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
</conditions>
<action type="Rewrite" url="/" />
</rule>
</rules>
</rewrite>


<httpCompression staticCompressionIgnoreHitFrequency="true" staticCompressionEnableCpuUsage="90">
<dynamicTypes>
<add mimeType="application/json" enabled="true" />
</dynamicTypes>
</httpCompression>

</system.webServer>
</configuration>
--- end ---

Твой сайт будет виден как https:\\web.site.com а rest api https:\\web.site.com\OData и т.к. они сидят на одном домене Angulаr HttpClient не будет генерировать CORS HTTP запросы совсем.

Если CORS напрягают и нет желания это отдельно конфигурировать в .config то можно это прибить гвоздями прямо в самом проекте прописав Application_BeginRequest в Global.asax.cs
Обрати внимание на Access-Control-Max-Age - этот параметер предотвращяет повторные CORS запросы.

--- Global.asax.cs ---
protected void Application_BeginRequest(object sender, EventArgs e)
{
EnableCrossDomain();
}

// Below was updated to only inserd hearder when OPTIONS found:
// https://www.devexpress.com/Support/Cent ... pplication
// https://www.codeproject.com/Articles/84 ... ORS-in-WCF

// <summary>
/// Enables cross domain POST, MERGE, DELETE for Firefox and Chrome
/// This requires:
/// <system.ServiceModel>
/// <serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
/// </summary>
static void EnableCrossDomain()
{
try
{
/* Logging
if (WebApiConfig.LogHeaders)
logger.Log(DEBUG, "EnableCrossDomain {0} {1}: \n{2}",
HttpContext.Current.Request.HttpMethod,
HttpContext.Current.Request.RawUrl,
String.Join(",", HttpContext.Current.Request.Headers.AllKeys));
*/

// https://stackoverflow.com/questions/471 ... cors-issue
// https://developer.mozilla.org/en-US/doc ... se-Headers
HttpContext.Current.Response.AddHeader("Access-Control-Expose-Headers", "*,Authorization,Content-Length,MYHEADER-X,MYHEADER-Y,MYHEADER-Z");

if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
{
string method = HttpContext.Current.Request.Headers["Access-Control-Request-Method"];
if (!string.IsNullOrEmpty(method))
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", method);

string headers = HttpContext.Current.Request.Headers["Access-Control-Request-Headers"];
if (!string.IsNullOrEmpty(headers))
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", headers);

HttpContext.Current.Response.AddHeader("Access-Control-Allow-Credentials", "true");

HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");

HttpContext.Current.Response.StatusCode = 204;
HttpContext.Current.Response.End();
}
}
catch (Exception ex)
{
//logger.Log(FATAL, ex);
}
}
}
--- end ---

Return to “Вопросы и новости IT”