Alienware m17 R3
上一台筆電是2013年買的Alienware M14x R2,拿來寫code已經有點慢了,最近終於找了機會買了新筆電,17吋螢幕真的比較適用啊。
不能免俗地附上配備表。
順帶一提,這次順便買了外星人背包,裝17吋筆電剛好,還有些空間可以裝我需要的東西,相當不錯。
這是2020/12月底買的,沒想到一忙就忘記貼文,直到現在。
最近好像沒啥能期待的MMO....
作者: Died |
|
Alienware m17 R3
作者: Died |
|
At this time, I am testing an old code build by .NET Core 2.0, when I tring to send request to the service, I always got 400 Bad Request, but I can know the service got request because I am running debug mode, it shows request coming and exception happend.
Since I can't find out the error just by 400 bad request, I open "Application Insights Search" in Visual Studio and found this error.
After some digging on stackoverflow, I found the error cause by a old version bug.
This question "Cannot debug in Visual Studio after changing the port number?" 's answer has good explain about this error.
You are getting this error message because Kestrel expected to run behind IIS, and received a direct request. And it noticed that because IIS was not there to inject the MS-ASPNETCORE-TOKEN header. --Gerardo Grignoli
Here have some options to solve the problem:
That's all,
作者: Died |
|
//set Support Cultures and default
services.Configure(options =>
{
var supportedCultures = new[]{
new CultureInfo("en-US"),
new CultureInfo("zh-TW"),
new CultureInfo("ja-JP")
};
options.DefaultRequestCulture = new RequestCulture("en-US");
options.SupportedCultures = supportedCultures;
options.SupportedUICultures = supportedCultures;
});
//set resource path
services.AddLocalization(options => options.ResourcesPath = "Resources");
private readonly IStringLocalizer _localizer;
public YourController(IStringLocalizerFactory factory)
{
_localizer = factory.Create("Message", System.Reflection.Assembly.GetExecutingAssembly().GetName().Name);
}
var str = _localizer["Cool"];
var str = _localizer[WeatherSummary.Cool.ToString()];
作者: Died |
|
System.NotSupportedException: The collection type 'System.Object' on 'somewhere.InnerResult.Data' is not supported.
at System.Text.Json.JsonPropertyInfoNotNullable`4.GetDictionaryKeyAndValueFromGenericDictionary(WriteStackFrame& writeStackFrame, String& key, Object& value)
at System.Text.Json.JsonPropertyInfo.GetDictionaryKeyAndValue(WriteStackFrame& writeStackFrame, String& key, Object& value)
at System.Text.Json.JsonSerializer.HandleDictionary(JsonClassInfo elementClassInfo, JsonSerializerOptions options, Utf8JsonWriter writer, WriteStack& state)
at System.Text.Json.JsonSerializer.Write(Utf8JsonWriter writer, Int32 originalWriterDepth, Int32 flushThreshold, JsonSerializerOptions options, WriteStack& state)
at System.Text.Json.JsonSerializer.WriteCore(Utf8JsonWriter writer, Object value, Type type, JsonSerializerOptions options)
at System.Text.Json.JsonSerializer.WriteCore(PooledByteBufferWriter output, Object value, Type type, JsonSerializerOptions options)
at System.Text.Json.JsonSerializer.WriteCoreString(Object value, Type type, JsonSerializerOptions options)
at System.Text.Json.JsonSerializer.Serialize[TValue](TValue value, JsonSerializerOptions options)
at TestWeb.Controllers.AuthController.VerifyToken(String token, Int32 tp) in C:\repos\somewhere\TestWeb\Controllers\AuthController.cs:line 51
public class InnerResult
{
public bool Success { get; set; } = true;
public int Code { get; set; }
public string Message { get; set; }
public dynamic Data { get; set; }
}
{
"success": true,
"code": 0,
"message": null,
"data": "vfu3MF5RFlQV9dWNQCFh6iRPNxeezFaV"
}
{
"success": true,
"code": 0,
"message": null,
"data": {
"name": "Died"
}
}
Install-Package Microsoft.AspNetCore.Mvc.NewtonsoftJson -Version 3.1.9
If you are using .NET core 2.x , add .AddNewtonsoftJson() after your AddMVC()
services.AddMvc().AddNewtonsoftJson();
If using .NET core 3.x , add it after what you have.
services.AddControllers().AddNewtonsoftJson();
services.AddControllersWithViews().AddNewtonsoftJson();
services.AddRazorPages().AddNewtonsoftJson();
Then no more this System.NotSupportedExceptio again.
作者: Died |
|
Handler/AuthorizeTokenHandler.cs
namespace Example.Handler
{
// Custom AuthorizationHandler for check token in claim
public class AuthorizeTokenHandler : AuthorizationHandler<TokenRequirement>
{
private readonly AuthService _auth;
public AuthorizeTokenHandler(AuthService auth)
{
_auth = auth;
}
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, TokenRequirement requirement)
{
//no token claim
if (!context.User.HasClaim(x => x.Type == "Token"))
{
context.Fail();
return Task.CompletedTask;
}
var username = context.User.FindFirst(ClaimTypes.Name).Value;
var token = context.User.FindFirst("Token").Value;
#region check token
if (_auth.CheckToken(username,token))
{
context.Succeed(requirement);
}
else
{
context.Fail();
}
#endregion
return Task.CompletedTask;
}
}
public class TokenRequirement : IAuthorizationRequirement
{
}
//handler
services.AddSingleton<IAuthorizationHandler, AuthorizeTokenHandler>();
//add policy
services.AddAuthorization(options =>
{
options.AddPolicy("TokenRequire", policy =>
policy.Requirements.Add(new TokenRequirement()));
});
[Authorize(Policy = "TokenRequire")]
[HttpPost]
public ApiResult SomeMethod()
{
}
作者: Died |
|
//set some claims first
var claims = new List<Claim>
{
new Claim(ClaimTypes.Name,"test name"),
new Claim("Token","token123"),
new Claim("Number","3")
//new Claim("dummy","dummy string")
};
var ci = new ClaimsIdentity(claims);
//most seen way, throw error if not exists
var name = ci.Claims.First(x => x.Type == ClaimTypes.Name).Value;
var token = ci.Claims.First(x => x.Type == "Token").Value;
//using FirstOrDefault() only, throw error if not exists
//var dunno = ci.Claims.FirstOrDefault(x => x.Type == "dunno").Value;
//fixed FirstOrDefault way: return null if not exists
var dunno = ci.Claims.Where(x => x.Type == "dunno").Select(x => x.Value).FirstOrDefault();
//safe way: using HasClaim to check
var dummy = ci.HasClaim(x => x.Type == "dummy")
? ci.Claims.First(x => x.Type == "dummy").Value
: null;
//short way: using FindFirst
var dummyShort = ci.FindFirst("dummy")?.Value;
//short way for int
int.TryParse(ci.FindFirst("Number")?.Value, out var number);
作者: Died |
|
作者: Died |
|
作者: Died |
|
//SwaggerConfig.cs
config.EnableSwagger(c =>
{
c.RootUrl(ResolveBasePath);
c.Schemes(new[] { "http", "https" });
}
internal static string ResolveBasePath(HttpRequestMessage message)
{
//fix for Cloudflare Flexible SSL and localhost test
var scheme = message.RequestUri.Host.IndexOf("localhost") > -1 ? "http://" : "https://";
return scheme + message.RequestUri.Authority;
}