我有一个奇怪的问题。我从我的 Android 应用程序中调用 ASP.NET Web API。我可以从应用程序发出 POST 请求,没有任何问题。但是,当我去发出 GET 请求时,请求返回“400 bad request invalid hostname”。这很奇怪,因为我可以发出 POST 请求,而不是 get 请求。我使用的 URL 是http://10.0.2.2/webapp/api/controllername(10.0.2.2,因为 android 模拟器使用 127.0.0.1;这是已发布的解决方法)。我确实启用了互联网权限。
我当前正在调试 Web API,并且可以调试 post 请求。我可以在 Internet Explorer 中手动输入获取请求的 URL,然后访问服务器。这就是我知道它起作用的方式。我有一个 application_beginrequest 的处理程序,只是为了查看我什至正在访问服务器,它是用于发布请求的。但我什至从未看到服务器收到 get 请求。
为了发出 Android GET 请求,我使用了以下内容(添加了带有附加信息的注释)。
//Creation of get request
HttpGet request = new HttpGet(url); //correct URL; verified
for(NameValuePair h : headers)
{
//6 headers added; verified OK
request.addHeader(h.getName(), h.getValue());
}
//Calls method shown below
return executeRequest(request, url);
private ResponseInformation executeRequest(HttpUriRequest request, String url) …Run Code Online (Sandbox Code Playgroud) 我正在向我的服务器发出 PATCH 请求以更新标题:
$.ajax({
url: Settings.get('serverURL') + 'Playlist/UpdateTitle',
type: 'PATCH',
dataType: 'json',
data: {
id: model.get('id'),
title: title
},
success: function () {
console.log("Success!");
},
error: function (error) {
console.error("Failure!");
}
});
[Route("UpdateTitle")]
[HttpPatch]
public IHttpActionResult UpdateTitle(PlaylistDto playlistDto)
{
using (ITransaction transaction = Session.BeginTransaction())
{
PlaylistManager.UpdateTitle(playlistDto.Id, playlistDto.Title);
transaction.Commit();
}
return Ok();
}
Run Code Online (Sandbox Code Playgroud)
除了执行 ajax 请求的错误回调而不是成功回调之外,一切都运行良好。
在Web API 2之前,我使用以下方法没有出现问题。显然,问题是我返回 Ok 结果而不是 JSON 成功对象:
[HttpPost]
public JsonResult UpdateTitle(Guid playlistId, string title)
{
using (ITransaction transaction = Session.BeginTransaction())
{
PlaylistManager.UpdateTitle(playlistId, title);
transaction.Commit();
} …Run Code Online (Sandbox Code Playgroud) 我开始通过下载 Swashbuckle 来运行项目“Swashbuckle.Dummy.SelfHost”。然后我转到浏览器并检查在program.cs类的主函数中声明的URL。当我在浏览器中给出相同的URL(例如“http:/ localhost:8090/swagger”)时,我收到以下错误。任何人都可以指导我逐步运行旋转扣解决方案并进行测试吗?如果我想在 IIS 上托管此应用程序并运行,我需要遵循哪些步骤?
An error has occurred.
Could not load file or assembly 'System.Net.Http.Formatting, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)
System.IO.FileLoadException
at Swashbuckle.Application.RedirectHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) at System.Net.Http.HttpMessageInvoker.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) at System.Web.Http.Dispatcher.HttpRoutingDispatcher.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) at System.Net.Http.DelegatingHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) at System.Web.Http.HttpServer.<>n__FabricatedMethod9(HttpRequestMessage , CancellationToken ) at System.Web.Http.HttpServer.d__0.MoveNext()
Run Code Online (Sandbox Code Playgroud) 在 asp.net web api 中,模型验证是通过 DataAnnotations 或 FluentValidation 框架完成的。
根据MS验证已完成:http://www.asp.net/web-api/overview/formats-and-model-binding/model-validation-in-aspnet-web-api
这是上面链接中的示例:
public class Product
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
public decimal Price { get; set; }
[Range(0, 999)]
public double Weight { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
Microsoft 似乎在简单示例中使用了 DTO/业务模型/持久性对象的组合...太糟糕了...它同时传递到客户端和数据库。
问题:像权重这样的东西必须在0到999之间,这不是属于服务层而不是应用层吗?
对我来说,这是业务逻辑,因为此字段类型(双精度)没有数据库限制,因此它肯定没有数据提供者逻辑。
我的印象是 wwwroot 目录不仅仅是一个普通文件夹。如何在 Visual Studio 2019 中将其添加到我的项目中?
我已将以下内容添加到 Startup.cs 文件中的 Configure 方法中:
app.UseDefaultFiles();
app.UseStaticFiles();
Run Code Online (Sandbox Code Playgroud)
我正在尝试为以下教程中的第 2 步执行此操作:https : //docs.microsoft.com/en-gb/aspnet/core/tutorials/web-api-javascript?view=aspnetcore-3.0
什么是 wwwroot 目录?只是一个普通文件夹还是其他什么?
我正在尝试在 github 中为这个项目进行 Entity Framework Core 迁移 - https://github.com/johnph/simple-transaction#WebApi-Endpoints
但是点击上面,如下图所示。我还将进行 EF 迁移的相同项目设置为“启动项目”。我试图搜索这个错误,但没有用。
我已经删除了现有的项目引用 dll,重新编译并重新添加了引用。我还重新安装了 Entity Framework Core 和其他一些 Nuget 包。最后,我可以毫无错误地清理和重建整个解决方案。
我唯一无法让它工作的是创建数据库的 EF 代码优先迁移。
是否可以使用 Kestrel 设置“aspNetCore requestTimeout”值(请参阅下面的 xml).......通过“代码”?
我在 KestrelServerLimits 对象上找不到任何东西。
下面是 xml 代码.......但希望在 CODE 中做到这一点,而不是通过(发布的)xml。
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.webServer>
<handlers>
<add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified"/>
</handlers>
<aspNetCore requestTimeout="00:20:00" processPath="%LAUNCHER_PATH%" arguments="%LAUNCHER_ARGS%" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" forwardWindowsAuthToken="false"/>
</system.webServer>
</configuration>
Run Code Online (Sandbox Code Playgroud)
我想下面的(“serverOptions.Limits.KeepAliveTimeout = TimeSpan.FromSeconds(5)”)......但是这并没有控制从我的邮递员测试服务器超时。
namespace MyStuff
{
using System;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
webBuilder.ConfigureKestrel(serverOptions =>
{
serverOptions.Limits.KeepAliveTimeout = TimeSpan.FromSeconds(5);
}); …Run Code Online (Sandbox Code Playgroud) 我有一个 LINQ 查询来查找过去 7 天的记录,效果很好。虽然如果我尝试使用相同的查询,但在过去 30 天内返回 0。谁能告诉我这是为什么?以及如何编辑查询以使其在过去 30 天内有效?
工作正常:
//calories burned working out over the last 7 days
public int CaloriesBurnedLast7Days
{
get
{
using (var db = new FitnessTrackerWebAPIContext())
{
int calsLast7Days = 0;
calsLast7Days = db.Workouts.Where(w => w.Date <= DateTime.Now.AddDays(-7) && w.UserID == ID).Sum(w => w.CaloriesBurned);
return calsLast7Days;
}
}
}
Run Code Online (Sandbox Code Playgroud)
不能正常工作:
//calories burned working out over the last 30 days
public int CaloriesBurnedLast30Days
{
get
{
using (var db = new FitnessTrackerWebAPIContext())
{
int calsLast30Days …Run Code Online (Sandbox Code Playgroud) 好吧,我将 Swagger 用于我的 API 文档,它在 localhost 中运行良好,当我将它托管在 IIS 上时,问题就开始了。出于某种原因,它不再起作用了
本地主机:
https://localhost:44381/swagger/index.html
Run Code Online (Sandbox Code Playgroud)
接口:
http://200.155.29.14/SimuladorFrete/Swagger/index.html
Run Code Online (Sandbox Code Playgroud)
当我在 ISS 中部署 Swagger 后尝试打开它时,我得到的只是一个空白页面和一个 500 内部服务器错误,这并没有说明异常。
这是我的配置方法(startup.cs)
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
app.UseSwagger();
app.UseStaticFiles();
app.UseSwaggerUI(c =>
{
if (env.IsDevelopment())
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "Web API V1");
}
else
{
// To deploy on IIS
c.SwaggerEndpoint("/SimulaFrete/swagger/v1/swagger.json", "Web API V1");
}
});
}
Run Code Online (Sandbox Code Playgroud)
这是我的 ConfigureServices 方法:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers().AddNewtonsoftJson();
services.AddSwaggerGen(c =>
{ …Run Code Online (Sandbox Code Playgroud) 我目前正处于项目的集成测试阶段,在尝试测试端点以查看我的数据库是否返回某些任务时遇到错误。我的域对象如下所示:
public class Task
{
public Guid Id { get; set; }
public string Title { get; set; }
public string Description { get; set; }
[Column(TypeName = "decimal(18,2)")]
public decimal? InitialPrice { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
我的端点的基本测试代码
[Fact]
public async Task Should_return_All_Tasks_with_ok_statusCode()
{
client.SetFakeBearerToken((object) token);
var response = await client.GetAsync("/api/v1/tasks");
response.StatusCode.Should().Be(HttpStatusCode.OK);
var json = await response.Content.ReadAsStringAsync();
var data = JsonConvert.DeserializeObject<List<Task>>(json);
data.Count.Should().BeGreaterThan(0);
}
Run Code Online (Sandbox Code Playgroud)
当我运行测试时出现错误
Newtonsoft.Json.JsonReaderException: Could not convert string to integer: 64fa643f-2d35-46e7-b3f8-31fa673d719b. Path '[0].id', line 1, position 45.
Run Code Online (Sandbox Code Playgroud)
我还尝试使用 webapi.client …
asp.net-web-api ×10
c# ×8
asp.net ×3
asp.net-core ×3
swagger ×2
.net-core ×1
ajax ×1
android ×1
http ×1
json.net ×1
linq ×1
swashbuckle ×1
validation ×1
wcf ×1