你好,
我的控制器中有两种方法,如果参数是某个值,我试图让一种方法触发,如果参数不是该值,则触发另一种方法。当参数等于某个值时,我的“not”方法就会触发。
根据(我的理解)这一点,我正确地编写了表达式。以下是这两个方法的签名:
@RequestMapping(value = "/doit", params= {"output=grouped", "display!=1"})
public @ResponseBody HashMap<String, Object> doSomething(
@RequestParam("text") String text,
@RequestParam("display") String display)
{
// this method runs if display=1 but why?
}
@RequestMapping(value = "/doit", params= {"output=grouped", "display=1"})
public @ResponseBody HashMap<String, Object> doSomethingElse(
@RequestParam("text") String text)
{
// this method is not being called when display=1...why not?
}
Run Code Online (Sandbox Code Playgroud)
我启用了 Spring 调试日志记录,并且看到 Spring 将参数转换为值为“1”的 RequestParam 字符串。然而,在下一行中,它决定将其映射到错误的方法。
我究竟做错了什么?
谢谢!
我有一个名为“items”的表和一个名为“ref_code”的 where 条件的输入。
$items = DB::table('items')
->where('ref_code','=', $request->ref_code)
->get(['id', 'ref_code', 'name','price']);
Run Code Online (Sandbox Code Playgroud)
但我似乎无法获取每一列的值。
我使用以下方法检查了查询构建器是否工作:
return $items;
Run Code Online (Sandbox Code Playgroud)
幸运的是,没有问题。
但是返回或获取单个值不适用于:
return $items->id
Run Code Online (Sandbox Code Playgroud)
我的语法错了吗?所有这些都在我的控制器中。
编辑:我试过了
dd($items);
Run Code Online (Sandbox Code Playgroud)
在返回之前,它向我展示了这个:
Collection {#325 ?
#items: array:1 [?
0 => {#322 ?}
]
}
Run Code Online (Sandbox Code Playgroud) 我正在使用 Rails 5 和 minitest。我想测试一个需要登录的控制器方法,由控制器中的过滤器验证
before_filter :require_current_user
def current_user
@current_user ||= User.find_by(id: session[:user_id])
end
def require_current_user
redirect_to(:root, :notice => "you must be logged in") unless current_user
end
Run Code Online (Sandbox Code Playgroud)
为了模拟会话变量,我在我的测试中添加了这个
def setup
@logged_in_user = users(:one)
session[:user_id] = @logged_in_user.id
end
test "do create" do
person = people(:one)
rating
post rate_url, params: {person_id: person.id, rating: rating}
# Verify we got the proper response
assert_response :success
end
Run Code Online (Sandbox Code Playgroud)
但是当我运行上面的测试时,它会导致错误
NoMethodError: undefined method `session' for nil:NilClass
test/controllers/rates_controller_test.rb:10:in `setup'
Run Code Online (Sandbox Code Playgroud)
如何在 minitest 中模拟会话变量?
编辑:根据给出的响应,这是我的 session_create 方法
def create …Run Code Online (Sandbox Code Playgroud) 我想调用我的控制器“Project”的方法“EditProject”,参数是项目的 Id。
我见过很多人使用 Ajax,但问题是我想调用控制器,然后控制器将用户重定向到视图“EditProject”,我不想停留在同一页面上
这是我在发现它不起作用之前尝试过的代码:
$('.edit-project').click(function (d) {
var id = $(this).attr('data-projectId');
$.ajax({
url: '@Url.Action("EditProject", "Project")',
data: { id: id },
type: "GET"
}).done(function() {
console.log("Done");
});
return false;
});Run Code Online (Sandbox Code Playgroud)
我也试过简单地使用
$.get("/Project/EditProject/" +id);
window.location.href = '@Url.Action("EditProject", "Project")' + '/' + id;
window.location.href = ("/Project/EditProject/" +id);
Run Code Online (Sandbox Code Playgroud)
但它返回 404 错误。
调用的方法非常简单:
[HttpGet]
[Authorize(Roles = "Professional")]
public async Task<IActionResult> EditProject(int id)
{
Project p = await _unitOfWork.Projects.GetById(id);
ViewData["Title"] = "Modification du challenge " + p.ProjectName;
return View(p);
}
Run Code Online (Sandbox Code Playgroud)
正如 Ajax 所预期的那样,它确实返回了视图,但它将它作为对 ajax 查询的响应返回,因此它不会按照我的意愿重定向和显示视图。
我项目中的所有控制器都从一个使用@ExceptionHandler注释的Base 控制器扩展而来 。看到我目前使用的比 spring 引入的处理异常的新方法有点老,我试图通过用ExceptionHandler最新的ResponseStatusException类替换我的注释来更新我的项目。
有关如何正确执行此操作的任何提示?
我是 Flurl 的新手。我正在尝试调用 api,我故意在参数中传递了无效的 apikey,然后 api 失败,说“禁止”并显示错误代码 403。我如何在异常中处理它?
public async Task<myResponse> MyService(myRequest request)
{
try
{
return await new Flurl.Url("https://myapi.com/rest/age?apikey=XXXXXXXX").PostJsonAsync(apirequest).ReceiveJson<myResponse>();
}
catch (FlurlHttpException ex)
{
var statusCode = await ex.GetResponseJsonAsync<myResponse>();
return await ex.GetResponseJsonAsync<myResponse>();
}
Run Code Online (Sandbox Code Playgroud)
如果我得到状态代码 403,我想抛出我自己的自定义异常,但目前它在线失败var statusCode = await ex.GetResponseJsonAsync<myResponse>();
}
我正在为 Shopware 6 构建一个插件,但似乎找不到任何关于如何扩展现有控制器操作的文档。我在 Shopware 中找到了如何向帐户控制器添加操作,但它似乎指的是 Shopware 5,我不确定我是否可以在 Shopware 6 中以这种方式使用它。
我想扩展的控制器操作是\Shopware\Storefront\Controller\AddressController::saveAddress- 在我的情况下,我想添加自定义地址验证,该验证将在我的插件中使用一项服务,其中将向第 3 方 API 发出请求,如果地址正确,则允许该地址,如果不正确然后返回一个错误。也许最好改为扩展,\Shopware\Core\Checkout\Customer\SalesChannel\AddressService::save但我现在不知道(一般来说我是 Shopware 的新手)。扩展服务意味着我不必覆盖整个操作逻辑,以便它在中间包含我的检查。或者也许有一个我可以用来保存地址的事件(同样的事情,找不到 Shopware6 的良好来源/事件列表)。
这里似乎有指南:https :
//docs.shopware.com/en/shopware-platform-dev-en/developer-guide/controller
和这里:https :
//docs.shopware.com/en/shopware-platform -dev-en/how-to/custom-storefront-controller
但这些只描述了如何制作一个新的控制器,它对我来说不是很有用,因为我不想添加任何新的路由而是使用现有的/account/address/create。
我将非常感谢如何在插件(配置,xml)中注册覆盖以及扩展类的代码示例。如果不是问太多,理想的答案将包含以下示例:
Shopware\Core\Framework\Validation\Exception\ConstraintViolationException)。我仍在探索 Laravel 8,但我的控制器的 store() 方法“未定义”有问题。
InvalidArgumentException Action PostsController@store 未定义。(查看:D:\Server\htdocs\app\resources\views\posts\create.blade.php)
我相信我实际上已经定义了它并且我使用了资源路线。
路线
Route::resource('posts', PostsController::class);
Run Code Online (Sandbox Code Playgroud)
刀刃
@extends('layouts.app')
@section('content')
<h1>Create Post</h1>
{!! Form::open(['action' => 'PostsController@store', 'method' => 'POST']) !!}
<div class="form-group">
{{Form::label('title', 'Title')}}
{{Form::label('title', ['class' => 'form-control','placeholder' =>'Title'])}}
</div>
<div class="form-group">
{{Form::label('body', 'Body')}}
{{Form::textarea('body', ['class' => 'form-control','placeholder' =>'Body'])}}
</div>
{{Form::submit('Submit',['class' =>'btn btn-primary'])}}
{!! Form::close() !!}
@endsection
Run Code Online (Sandbox Code Playgroud)
控制器
class PostsController extends Controller
{
public function create()
{
return view('posts.create');
}
public function store(Request $request)
{
$this->validate($request, [
'title' => 'required',
'body' => 'required'
]); …Run Code Online (Sandbox Code Playgroud) 我注意到是否使用此属性是一样的。我错了吗?
举个例子:
[Route("[controller]")]
[ApiController]
public class DataTablesController: ControllerBase
{
[HttpGet]
public IActionResult Test()
{
return Ok("test");
}
}
Run Code Online (Sandbox Code Playgroud)
当我删除该[ApiController]属性时什么也没发生。
在微软的文档中,我找到了这样的解释:
指示类型和所有派生类型用于提供 HTTP API 响应。
使用此属性修饰的控制器配置了旨在改善开发人员构建 API 体验的功能和行为。
在程序集中装饰时,程序集中的所有控制器都将被视为具有 API 行为的控制器。
什么是 API 行为?我们为什么要使用它?
c# controller asp.net-apicontroller .net-attributes asp.net-core
public function fetchdrug(Request $search_drug){
$filter_drug = $search_drug->input('search_drug');
$all_drugs = HmsBbrKnowledgebaseDrug::selectRaw('DISTINCT ON (drug_code)
drug_code,
drug_name,
JSON_AGG(drug_dosage) AS dosage_list')
->GroupBy('drug_code', 'drug_name')
->orderBy('drug_code', 'ASC')
->get();
return response()->json([
'all_drugs'=>$all_drugs,
]);
}
Run Code Online (Sandbox Code Playgroud)
我正在使用JSON_AGG检索多行drug_dosage并将它们合并为一行,但是我的输出中出现了括号和引号,我该如何将其取出?
更新:我在示例中遇到错误,因为我正在尝试使用str_replace和 的解决方案preg_replace。我的问题是目标在 SQL 语句中,所以我怀疑这与错误有关,因为结果错误中还有其他数据:
Uncaught TypeError: Cannot use 'in' operator to search for 'length' in
{"drug_code":"CFZU",
"drug_name":"Cefazolin",
"dosage_list":"[\"<=4 mg\/L\", \"<=3 mg\/L\"]"},
{"drug_code":"TZPD","drug_name":"Pip\/Tazobactam",
"dosage_list":"[\"Pip\/Tazobactam\"]"}
Run Code Online (Sandbox Code Playgroud) controller ×10
laravel ×3
c# ×2
php ×2
spring ×2
asp.net-core ×1
flurl ×1
frameworks ×1
function ×1
java ×1
javascript ×1
laravel-8 ×1
minitest ×1
plugins ×1
session ×1
shopware ×1
shopware6 ×1
spring-mvc ×1
sql ×1
unit-testing ×1