Web API 是一种用于构建 RESTful 服务的框架,它允许客户端通过 HTTP 请求与服务器进行交互。ASP.NET Core Web MVC 是 ASP.NET Core 框架中的一个组件,用于构建基于 MVC(Model-View-Controller)模式的 Web 应用程序。
要从 Web API 调用 ASP.NET Core Web MVC,通常有以下几种方式:
HttpClient 是 .NET 中用于发送 HTTP 请求的类。以下是一个简单的示例:
using System;
using System.Net.Http;
using System.Threading.Tasks;
public class ApiClient
{
private readonly HttpClient _httpClient;
private const string BaseUrl = "https://your-api-url.com";
public ApiClient(HttpClient httpClient)
{
_httpClient = httpClient;
}
public async Task<string> GetAsync(string endpoint)
{
var response = await _httpClient.GetAsync($"{BaseUrl}/{endpoint}");
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync();
}
public async Task<string> PostAsync(string endpoint, string content)
{
var response = await _httpClient.PostAsync($"{BaseUrl}/{endpoint}", new StringContent(content));
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync();
}
}
RestSharp 是一个流行的第三方库,用于简化 HTTP 请求。以下是一个简单的示例:
using RestSharp;
public class ApiClient
{
private readonly RestClient _restClient;
private const string BaseUrl = "https://your-api-url.com";
public ApiClient()
{
_restClient = new RestClient(BaseUrl);
}
public async Task<string> GetAsync(string endpoint)
{
var request = new RestRequest(endpoint, Method.GET);
var response = await _restClient.ExecuteAsync(request);
response.ErrorException?.ThrowIfNotNull();
return response.Content;
}
public async Task<string> PostAsync(string endpoint, string content)
{
var request = new RestRequest(endpoint, Method.POST);
request.AddParameter("application/json", content, ParameterType.RequestBody);
var response = await _restClient.ExecuteAsync(request);
response.ErrorException?.ThrowIfNotNull();
return response.Content;
}
}
如果你在前端使用 jQuery,可以使用 AJAX 方法来调用 Web API。以下是一个简单的示例:
$(document).ready(function() {
$.ajax({
url: "https://your-api-url.com/endpoint",
type: "GET",
success: function(data) {
console.log(data);
},
error: function(xhr, status, error) {
console.error(error);
}
});
});
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy("AllowAllOrigins",
builder =>
{
builder.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod();
});
});
services.AddControllers();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseCors("AllowAllOrigins");
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = Configuration["Jwt:Issuer"],
ValidAudience = Configuration["Jwt:Audience"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:SecretKey"]))
};
});
services.AddControllers();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
希望这些信息对你有所帮助!
领取专属 10元无门槛券
手把手带您无忧上云