对于我的一个项目,我使用的是带有SOA架构的Web API.在Controller中,我希望捕获异常(由Repository抛出)并返回HttpResposeMessage.
我想要的是应该有一个继承ApiController(class BaseController : ApiController)的BaseController ,我的每个Controller应该由baseController继承,
例如class TaskController : BaseController,如果我的控制器中发生任何异常,那么应该由它来处理BaseController.演示:
以下是VS解决方案中的项目:(项目结构)
XYZ.Model
XYZ.Repository
XYZ.WebServices
XYZ.Exception
XYZ.UI
Run Code Online (Sandbox Code Playgroud)
代码:XYZ.Model
public class Error
{
public string Code { get; set; }
public string Message { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
XYZ.Exception
// To create the custom exception as per our need
public class BaseException : Exception
{
private Error _error;
public Error Error
{
get { return _error; }
}
public BaseException()
{
_error = …Run Code Online (Sandbox Code Playgroud) 我需要构建一个ASP.NET Core 2.0 Web API应用程序,该应用程序将能够完成自定义XML输入和输出格式。
我已经成功设置了一个自定义输出格式化程序,但是没有一个自定义输入格式化程序。
更准确地说,这是启动配置:
public void ConfigureServices(IServiceCollection services)
{
services
.AddMvc(opt =>
{
opt.ReturnHttpNotAcceptable = true;
opt.OutputFormatters.Clear();
opt.InputFormatters.Clear();
opt.InputFormatters.Add(new SoapInputFormatter());
opt.OutputFormatters.Add(new SoapOutputFormatter());
});
}
Run Code Online (Sandbox Code Playgroud)
这个想法是具有定制的SOAP输入和输出格式。不,现有的XmlDataContractSerializerInputFormatter不会。
本SoapOutputFormatter类:
public class SoapOutputFormatter : IOutputFormatter
{
public bool CanWriteResult(OutputFormatterCanWriteContext context)
{
return true;
}
public async Task WriteAsync(OutputFormatterWriteContext context)
{
var bytes = Encoding.UTF8.GetBytes(context.Object.ToString());
await context.HttpContext.Response.Body.WriteAsync(bytes, 0, bytes.Length);
}
}
Run Code Online (Sandbox Code Playgroud)
和SoapInputFormatter班级:
public class SoapInputFormatter : InputFormatter
{
public override Task<InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context)
{
throw new …Run Code Online (Sandbox Code Playgroud) c# asp.net-web-api asp.net-core asp.net-core-2.0 inputformatter
我在SO上发现了以下评论:
"同样使用async await模式和更新版本的.Net将使效率更接近NodeJS和Nginx等事件驱动架构的效率"
我继承了一个Web API应用程序,基本上所有层中的所有方法都利用了async/await模式.以上关于async/await性能的评论非常引人注目.在Web API应用程序中的所有层的所有方法上实现async/await是否合适?是否有任何情况我应该避免等待/异步或小心不要过度使用它?
我需要在服务器上存储二进制数据 - 每个项目大约2K.我之前从未在sql server中使用过varbinary类型.我正在考虑两种选择:
我意识到在第一个选项中,数据库上的负载是最小的.但是,需要考虑文件IO.
与DB交互的应用程序是.NET RESTFull WebAPI(c#).目标表中的总行数为4-5千.
在这种情况下,最佳做法是什么?
我在Asp.Net Core WebApi项目中工作,并创建了一个角色“ admin”并将其添加到我的用户中。但是,如果我以管理员身份登录,第一种方法将返回“ This is admin!”。,但是第二种方法返回错误403 Forbidden。
如果我从Authorize属性中删除Roles参数,一切都会很好。我不明白为什么我无法访问第二种方法,因为我的用户具有管理员角色。
// Host/api/roles/getroles
[Authorize]
[HttpGet]
public async Task<IEnumerable<string>> GetRoles()
{
var user = await _userManager.GetUserAsync(User);
bool isAdmin = await _userManager.IsInRoleAsync(user, Roles.AdminRole);
if (isAdmin)
return new[] {"This is admin!"};
return await _userManager.GetRolesAsync(user);
}
// ===== Admin Methods =====
// Host/api/roles/createrole
[Authorize(Roles = Roles.AdminRole)]
[HttpPost]
public async Task<IActionResult> CreateRole([FromBody] CreateRoleViewModel model)
{
if (!ModelState.IsValid)
{
return BadRequest();
}
var result = await _roleManager.CreateAsync(new IdentityRole(model.RoleName));
if (!result.Succeeded)
return BadRequest(result); …Run Code Online (Sandbox Code Playgroud) 只要是关于Web API的新手。
网络Api:
[HttpGet]
public IHttpActionResult Test()
{
var doc = new XmlDocument();
XmlElement tournament = (XmlElement)doc.AppendChild(doc.CreateElement("Tournament"));
XmlElement match = (XmlElement)tournament.AppendChild(doc.CreateElement("Match"));
match.SetAttribute("ID", "SomeMatch");
return Ok(doc.InnerXml);
}
Run Code Online (Sandbox Code Playgroud)
结果:
<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/"><Tournament><Match ID="SomeMatch" /></Tournament></string>
两个问题:
以及如何取回
<Tournament>
<Match ID="SomeMatch" /></Tournament>
Run Code Online (Sandbox Code Playgroud) 我有2个项目的解决方案:Asp.Net WebApi Core和WinForms.我将使用WinForm的服务.
更改了解决方案属性以启动多个项目:第一个WebApi然后是WinForm(主窗体是FORM1).
现在,我有如下的简单代码:
private void button1_Click(object sender, EventArgs e)
{
TestAutentication().Wait();
Console.ReadKey();
}
static async Task TestAutentication()
{
HttpClientHandler handler = new HttpClientHandler();
handler.UseDefaultCredentials = true;
using (var client = new HttpClient(handler))
{
client.BaseAddress = new Uri("http://localhost:53791");
try
{
HttpResponseMessage response = await client.GetAsync("api/ValuesController");
if (response.IsSuccessStatusCode)
{
var result = await response.Content.ReadAsAsync<string>();
Console.WriteLine("{0}", result);
}
else
{
Console.WriteLine("{0}", response.ReasonPhrase);
}
}
catch (HttpRequestException ex)
{
Console.WriteLine("{0}", ex.Message);
}
}
}
Run Code Online (Sandbox Code Playgroud)
在启动浏览器期间打开然后打开FORM1.在执行该行时单击button1调试器:
HttpResponseMessage response = await client.GetAsync("api/ValuesController");
悬挂的原因是什么?
提前致谢.
我正在尝试使用asp.net Identity Core保护我的webAPI。现在,我想动态创建角色,并在我的管理面板中对其进行设置/删除权限。
例如,我有此权限列表:
现在,我想创建不同的角色,并根据需要为他们设置此权限,并将这些角色分配给每个用户。
我在Identity框架的UserManager和RoleManager中进行了搜索,但是无法创建此功能。
有没有实现此功能的方法?我觉得这很有用,但这是关于dotnet的
我有一个控制台应用程序,它的工作原理像网络api一样退出。我在Program.cs上注册
var collection = new ServiceCollection();
collection.AddScoped<IInfoBusinessComponent, InfoBusinessComponent>();
Run Code Online (Sandbox Code Playgroud)
在添加InfoBusinessComponent之前,InfoBusinessComponent还需要进行依赖项注入。我也注册我的ILogger。
在我的InfoController上,我像这样使用di:
public InfoController(IInfoBusinessComponent businessComponent, ILogger<InfoController> logger)
Run Code Online (Sandbox Code Playgroud)
当我现在呼叫该端点时,我立即收到500响应。当我从控制器中删除参数时,该过程将进入构造函数和控制器。但这不是我想要的。
public InfoController()
Run Code Online (Sandbox Code Playgroud)
为什么构造函数没有得到依赖注入或为什么没有调用构造函数?
public class Program
{
#region fields and propetries
public IConfiguration Configuration { get; }
//# if DEBUG
//#endif
public static IConnection Connection { get; set; }
public static ITimeSeriesBusinessComponent TimeSeriesBusinessComponent { get; set; }
public static IInfoBusinessComponent InfoBusinessComponent { get; set; }
private static int counter;
#endregion fields and propetries
public static void Main(string[] args)
{
IConfiguration config = GetConfigurations();
ILogger …Run Code Online (Sandbox Code Playgroud) 我有一个方法定义为:
public Task<ReturnsMessage> Function() {
var task = Task.Run(() =>
{
var result = SyncMethod();
return new ReturnMessage(result);
});
if (task.Wait(delay)) {
return task;
}
var tcs = new TaskCompletionSource<ReturnMessage>();
tcs.SetCanceled();
return tcs.Task;
}
Run Code Online (Sandbox Code Playgroud)
现在在基于maxAttempts值的循环中调用它:
(方法名RetryableInvoke)
for (var i = 0; i < maxAttempts; i++)
{
try
{
return Function().Result;
}
catch (Exception e)
{
}
}
Run Code Online (Sandbox Code Playgroud)
它工作正常,但是当负载很大时,我发现线程急剧增加,转储向我显示此警告:
asp.net-web-api ×10
c# ×9
asp.net-core ×4
async-await ×3
.net ×2
.net-core ×2
asynchronous ×1
deadlock ×1
formatter ×1
soa ×1
sql ×1
sql-server ×1
xml ×1